<?php

namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\facade\Session;
use think\facade\Validate;

class Comment extends BaseController
{
    // 发表评论
    public function save()
    {
        !$this->request->checkToken() && die(json_encode(['code' => 1, 'msg' => '令牌数据无效']));
        $user = Session::get('user');
        empty($user['id']) && die(json_encode(['code' => 1, 'msg' => '请先登录']));
        $user = Db::table('users')->where('id', $user['id'])->find();
        !$user && die(json_encode(['code' => 1, 'msg' => '用户不存在']));
        $data['name'] = $user['name'] ?: '匿名';
        $data['post_id'] = (int)input('post.post_id');
        $article = Db::table('article')->where('id', $data['post_id'])->find();
        !$article && die(json_encode(['code' => 1, 'msg' => '文章不存在']));
        $data['comment'] = input('post.comment');
        !$data['comment'] && die(json_encode(['code' => 1, 'msg' => '输入评论内容']));
        $check = Db::table('comment')->where('comment', $data['comment'])->select()->toArray();
        $check && die(json_encode(['code' => 1, 'msg' => '评论已存在']));
        $data['pid'] = (int)input('post.pid');
        $data['uid'] = $user['id'];
        $data['status'] = 0;
        $data['add_time'] = time();
        Db::table('comment')->insert($data);
        Db::table('article')->where('id', $data['post_id'])->inc('comments')->update();
        echo json_encode(['code' => 0, 'msg' => '提交成功', 'data' => $data]);
    }
}
